package util.parser;

import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import util.io.URLInput;
import util.string.StringAnalysis;

public class JsonParser {

	/**
	 * @param args
	 */

	/**
	 * Parse Delicious ULR-info post obtained in JSON format from
	 * 
	 * http://feeds.delicious.com/v2/json/urlinfo/
	 * 
	 * 
	 */

	public static DeliciousURLInfoPost parseDeliciousInfoPost(String post) {

		Object obj = JSONValue.parse(post);
		JSONArray array = (JSONArray) obj;

		DeliciousURLInfoPost del_post = new DeliciousURLInfoPost();

		if (array != null && array.size() > 0) {
			JSONObject obj2 = (JSONObject) array.get(0);

			if (obj2.containsKey("title")) {

				del_post.setTitle(obj2.get("title").toString().trim());

			}

			if (obj2.containsKey("url")) {

				del_post.setUrl(obj2.get("url").toString().trim());

			}

			if (obj2.containsKey("total_posts")) {

				String tmp = obj2.get("total_posts").toString().trim();
				del_post.setTotal_posts(Long.valueOf(tmp));

			}

			if (obj2.containsKey("hash")) {

				del_post.setTitle(obj2.get("hash").toString().trim());

			}

			if (obj2.containsKey("top_tags")) {
				if (obj2.get("top_tags").getClass().getCanonicalName().equals(
						"org.json.simple.JSONObject")) {
					JSONObject obj3 = (JSONObject) obj2.get("top_tags");

					Iterator<String> keys = obj3.keySet().iterator();

					Hashtable<String, Long> hash = del_post.getFrequent_tags();
					while (keys.hasNext()) {

						String key = keys.next();
						hash.put(key, Long.valueOf(obj3.get(key).toString()
								.trim()));

					}

				} else {
					JSONArray obj3 = (JSONArray) obj2.get("top_tags");
					

					
				}

			}

		}

		if (del_post.getUrl() == null)
			return null;

		return del_post;

	}

	/**
	 * 
	 * Parse JSON url post in delicious
	 * 
	 * 
	 * @param url
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static DeliciousURLInfoPost parseDeliciousInfoFromURL(String url) {
		// hash url to MD5

		if (!url.startsWith("http")) {

			url = "http:// " + url;

		}

		String md5 = null;
		try {
			md5 = StringAnalysis.hashStringMD5(url);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String del_url = " http://feeds.delicious.com/v2/json/urlinfo/" + md5;

		String post = URLInput.readFromURL(del_url);

		DeliciousURLInfoPost del = parseDeliciousInfoPost(post);

		return del;

	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		// TODO Auto-generated method stub

		String url = "http://feeds.delicious.com/v2/json/urlinfo/441c2835a8c2ec794eb2b4a52091c745";

		url ="http://www.funbrain.com/words.html";
		System.out.println(parseDeliciousInfoFromURL(url));

	}

}
